c<template>
  <div class="app-main-container">
    <div class="doumee-filter">
      <el-form inline @submit.native.prevent>
        <el-form-item label="场馆:">
          <el-select v-model="filters.venueId" placeholder="选择场馆">
            <el-option
              v-for="item in venueList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择时间段:">
          <el-date-picker
            v-model="filters.time"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="默认当天"
            end-placeholder="默认当天"
            style="margin-right: 10px; height: 40px; margin-bottom: 10px"
            :clearable="false"
            @blur="dateIndex = 0"
          />
        </el-form-item>
        <!-- <el-form-item>
          <div class="flex tabDate">
            <div :class="dateIndex === 1 ?'on':''" @click="getDate(1)">昨日</div>
            <div :class="dateIndex === 2 ?'on':''" @click="getDate(2)">本周</div>
            <div :class="dateIndex === 3 ?'on':''" @click="getDate(3)">本月</div>
          </div>
        </el-form-item> -->
        <el-form-item>
          <el-button v-preventReClick type="primary" @click="getDataList()">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="doumee-table-buttons">
      <el-button v-preventReClick type="primary" @click="exportExcel">导出</el-button>
    </div>
    <el-table
      ref="tableRef"
      :data="list"
      border
      fit
      show-summary
      :span-method="objectSpanMethod"
      :summary-method="getSummaries"
      :header-row-class-name="'table-header'"
      class="doumee-element-table table_tj"
    >
      <el-table-column
        prop="date"
        label="日期"
        min-width="200"
        align="center"
      />
      <el-table-column
        prop="venueName"
        align="center"
        label="场馆"
        min-width="200"
      />
      <el-table-column label="营业收入" align="center">
        <el-table-column
          prop="cash"
          label="现金"
          align="center"
          min-width="200"
        />
        <el-table-column
          prop="member"
          label="会员卡"
          align="center"
          min-width="200"
        />
        <el-table-column
          prop="weChat"
          label="微信"
          align="center"
          min-width="200"
        />
        <el-table-column
          prop="aliPay"
          label="支付宝"
          align="center"
          min-width="200"
        />
        <el-table-column
          prop="transfer"
          label="转账"
          align="center"
          min-width="200"
        />

      </el-table-column>
      <el-table-column
        prop="sum"
        label="合计"
        min-width="200"
        align="center"
      />
    </el-table>
    <div class="flex-cc doumee-pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-page.sync="cur_page"
        :hide-on-single-page="true"
        @current-change="getList"
      />
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import { parseTime } from '@/utils/index'
import { venueList, businessSettlement } from '@/api'
import { getFMdate } from '@/utils/index'
import { queryFormConfig } from './config'
export default {
  name: 'BusinessStatistics',
  data() {
    return {
      venueList: [],
      list: [],
      queryFormConfig,
      pagination: {
        page: 1,
        rows: 10,
        firstQueryTime: new Date()
      },

      total: 0,
      dateIndex: 1,
      weekList: [],
      filters: {
        venueId: ''
      },
      meta: []
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.setDate(new Date())
    this.getVenueList()
  },
  methods: {
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        } else if (index === 1) {
          sums[index] = '-'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        } else {
          sums[index] = '-'
        }
      })
      for (var key = 1; key <= sums.length; key++) {
        const number = sums[key]
        if (!isNaN(number)) {
          sums[key] = parseFloat(number).toFixed(2)
        }
      }
      return sums
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        var rowm = this.mergeList[rowIndex] - rowIndex
        var rowidx = this.mergeIndexList[rowIndex]
        if (rowIndex === rowidx) {
          return {
            rowspan: rowm,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      } else {
        return {
          rowspan: 1,
          colspan: 1
        }
      }
    },
    getDataList() {
      const param = this.filters
      if (param.time && param.time.length > 0) {
        param.startTime = param.time[0]
        param.endTime = param.time[1]
      } else {
        param.startTime = ''
        param.endTime = ''
      }
      businessSettlement({
        param
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode !== '000000') return
          const dataList = res.recordList
          const recordList = []
          const mergeList = []
          const mergeIndexList = []
          var colnum = 0
          var idx = 0
          dataList.forEach((e) => {
            colnum += e.responseList.length
            e.responseList.forEach((s) => {
              s['cardTypeName'] = e['cardTypeName']
              mergeList.push(colnum)
              recordList.push(s)
              mergeIndexList.push(idx)
            })
            idx += e.responseList.length
          })
          this.list = recordList
          this.mergeList = mergeList
          this.mergeIndexList = mergeIndexList
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    // 获取场馆列表
    getVenueList() {
      venueList({
        param: { flag: '0' }
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode !== '000000') return
          this.venueList = res.recordList
          this.getDate(1)
          this.getDataList()
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    getDate(e) {
      this.dateIndex = e
      if (e === 1) {
        this.$set(this.filters, 'time', [getFMdate(-1, '-').slice(0, 10), getFMdate(-1, '-').slice(0, 10)])
      } else if (e === 2) {
        this.$set(this.filters, 'time', [this.weekList[0].value, this.weekList[6].value])
      } else {
        var date = new Date()
        var year = date.getFullYear() + '-'
        var month = this.calculation(date.getMonth() + 1) + '-'
        var day = new Date(date.getFullYear(), date.getMonth() + 1, 0)
        this.$set(this.filters, 'time', [year + month + '01', year + month + day.getDate()])
      }
    },
    calculation(s) {
      return s < 10 ? '0' + s : s
    },
    formatDate(date) {
      const year = date.getFullYear() + '-'
      const month = this.calculation(date.getMonth() + 1) + '-'
      const day = this.calculation(date.getDate())
      const week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()]
      return {
        label: month + day + ' ' + week,
        value: year + month + day,
        old: new Date(date)
      }
    },
    addDate(date, n) {
      date.setDate(date.getDate() + n)
      return date
    },
    setDate(date) {
      var week = date.getDay() - 1
      if (week === -1) {
        week = 6
      }
      date = this.addDate(date, week * -1)
      this.currentDate = new Date(date)
      const arr = []
      for (var i = 0; i < 7; i++) {
        arr[i] = this.formatDate(i === 0 ? date : this.addDate(date, 1))
      }
      this.weekList = arr
    },
    exportExcel() {
    /* generate workbook object from table */
      var xlsxParam = { raw: true } // 导出的内容只做解析，不进行格式转换
      var wb = XLSX.utils.table_to_book(document.querySelector('.doumee-element-table'), xlsxParam)
      /* get binary string as output */
      var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      // 设置当前日期
      const time = new Date()
      const year = time.getFullYear()
      const month = time.getMonth() + 1
      const day = time.getDate()
      const filename = year + '' + month + '' + day + '营业结算统计' + '.xlsx'
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), filename)
      } catch (e) {
        if (typeof console !== 'undefined') {
          console.log(e, wbout)
        }
      }
      return wbout
    }
  }
}
</script>
<style scoped lang="scss">
.tabDate {
  display: flex;
  div {
    background-color: #F5F7FA;
    color:#111111;
    display: inline-block;
    padding: 0 20px;
    height: 36px;
    line-height: 36px;
    box-sizing: border-box;
    cursor: pointer;
    &:nth-of-type(2){
      border-left: 1px solid #DCDFE6;
      border-right: 1px solid #DCDFE6;
    }
    &.on {
      color: #fff;
      background-color: #435EBE;
    }
  }
}
</style>
